package com.isoftstone.plugin.freemark;

import com.isoftstone.util.Logger;
import freemarker.core.Environment;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;

import java.io.IOException;
import java.io.Writer;

/**
 * @描述：
 * @author：guoX
 * @date：2017/7/12
 */
public class FreemarkerExceptionHandler implements TemplateExceptionHandler {
    protected Logger logger = Logger.getLogger(this.getClass());
    @Override
    public void handleTemplateException(TemplateException te, Environment env, Writer out)  {
        logger.error("[Freemarker Error: " + te.getMessage() + "]");
        String missingVariable = "undefined";
        try {
            String[] tmp = te.getMessageWithoutStackTop().split("\n");
            if (tmp.length > 1)
                tmp = tmp[1].split(" ");
            if (tmp.length > 1)
                missingVariable = tmp[1];
            out.write("[出错了，请联系网站管理员：${ " + missingVariable
                    + "}]");
            logger.error("[出错了，请联系网站管理员]", te);
        } catch (IOException e) {
            e.printStackTrace();

        }
    }
}